package com.example.tangyee.fragment;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.TextView;

import com.example.tangyee.R;
import com.example.tangyee.activity.HealthVideoPlayerActivity;
import com.example.tangyee.activity.KnowledgeDetailActicity;
import com.example.tangyee.activity.RecipeDetailActivity;
import com.example.tangyee.bean.HealthVideo;
import com.example.tangyee.bean.Recipe;
import com.example.tangyee.utils.SessionidUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class SearchResultFragment extends Fragment {

    private static final String TAG = "SearchResultFragment";

    private static final String PARAM1 = "param1";
    private static final String PARAM2 = "param2";

    private String key;
    private String type;

    /*控制懒加载*/
    boolean mIsPrepare = false;		//视图还没准备好
    boolean mIsVisible= false;		//不可见
    boolean mIsFirstLoad = true;	//第一次加载

    public static SearchResultFragment newInstance(String key, String value) {
        SearchResultFragment fragment = new SearchResultFragment();
        Bundle args = new Bundle();
        args.putString(PARAM1, key);
        args.putString(PARAM2, value);
        fragment.setArguments(args);
        return fragment;
    }

    private Unbinder mUnbinder;

    @BindView(R.id.loading_view)
    View loadingView;

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    private DataAdapter mAdapter;
    private LinearLayoutManager layoutManager;

    private SearchTask mSearchTask;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        key = getArguments().getString(PARAM1);
        type = getArguments().getString(PARAM2);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        /*控制懒加载*/
        mIsPrepare = true;
        lazyLoad();
    }

    /*控制懒加载*/
    private void lazyLoad() {
        if (!mIsPrepare || !mIsVisible || !mIsFirstLoad) {
            return;
        }

        loadData();
        mIsFirstLoad = false;
    }

    /*加载数据*/
    private void loadData() {
        mSearchTask = new SearchTask(key, type);
        mSearchTask.execute();
    }

    /*控制懒加载*/
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            mIsVisible = true;
            lazyLoad();
        } else {
            mIsVisible = false;
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.search_result_for_view_pager, container, false);
        mUnbinder = ButterKnife.bind(this,view);
        initView();

        return view;
    }

    private void initView() {
        mAdapter = new DataAdapter();
        layoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setLayoutManager(layoutManager);
    }

    private class SearchTask extends AsyncTask<Void, Void, Map<String, String>> {

        private StringBuilder url = new StringBuilder("https://www.tangyee.com/Mui/Page/SearchList?");

        public SearchTask(String key, String type) {
            url.append("key=" + key + "&type=" + type);
        }

        @Override
        protected Map<String, String> doInBackground(Void... voids) {
            Map<String, String> map = new LinkedHashMap<>();
            if (isCancelled()) {
                return map;
            }
            try {
                SessionidUtils.updateSessionId(getActivity());
                Document document = Jsoup.connect(url.toString()).cookie("ASP.NET_SessionId", SessionidUtils.getSessionId(getActivity())).get();
                Elements as = document.select("ul.ranking-table>li>a");
                for (Element a : as) {
                    map.put(a.attr("href"), a.text());
                }
            } catch (SocketTimeoutException ste) {
                Log.e(TAG, "doInBackground: ", ste);
                return null;
            } catch (IOException e) {
                Log.e(TAG, "doInBackground: ", e);
                return null;
            }
            return map;
        }

        @Override
        protected void onPostExecute(Map<String, String> stringStringMap) {
            if (stringStringMap == null) {
                loadingView.findViewById(R.id.progressBar).setVisibility(View.GONE);
                TextView textView = loadingView.findViewById(R.id.loading);
                textView.setText("服务器异常。");
                return;
            }
            if (stringStringMap.size() == 0) {
                loadingView.findViewById(R.id.progressBar).setVisibility(View.GONE);
                TextView textView = loadingView.findViewById(R.id.loading);
                textView.setText("没有找到记录。");
                return;
            }
            loadingView.setVisibility(View.GONE);
            mAdapter.setMap(stringStringMap);

            ScaleAnimation sa = new ScaleAnimation(1f, 1f, 1.1f, 1f,
                    Animation.RELATIVE_TO_SELF, 0f,
                    Animation.RELATIVE_TO_SELF, 0f);
            sa.setDuration(1000);

            AlphaAnimation aa = new AlphaAnimation(0, 1);
            aa.setDuration(1000);

            AnimationSet as = new AnimationSet(true);
            as.setDuration(1000);
            as.addAnimation(sa);
            as.addAnimation(aa);
            mRecyclerView.startAnimation(as);
        }

    }


    private class DataAdapter extends RecyclerView.Adapter<DataViewHolder> {

        Map<String, String> mMap = new LinkedHashMap<>();

        public void setMap(Map<String, String> map) {
            mMap = map;
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public DataViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            return new DataViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.my_simple_list_item,viewGroup,false));
        }

        @Override
        public void onBindViewHolder(@NonNull DataViewHolder dataViewHolder, int i) {
            Map.Entry<String, String>[] entries = new Map.Entry[mMap.size()];
            mMap.entrySet().toArray(entries);
            Map.Entry<String, String> entry = entries[i];
            dataViewHolder.title.setText(mMap.get(entry.getKey()));

            String[] ss = entry.getKey().split("/");
            String id = ss[ss.length - 1];
            dataViewHolder.title.setOnClickListener(v -> {
                if ("know".equals(type)) {
                    Intent intent = new Intent(getActivity(), KnowledgeDetailActicity.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt("knowID", Integer.valueOf(id));
                    bundle.putString("title", mMap.get(entry.getKey()));
                    intent.putExtras(bundle);
                    getActivity().startActivity(intent);
                } else if ("recipe".equals(type)) {
                    Recipe recipe = new Recipe();
                    recipe.setId(Integer.valueOf(id));
                    recipe.setRecipeName(entry.getValue());
                    Intent intent = RecipeDetailActivity.getRecipeDetailActivityIntent(getActivity(), recipe);
                    getActivity().startActivity(intent);
                } else if ("video".equals(type)) {
                    HealthVideo healthVideo = new HealthVideo();
                    healthVideo.setTitle(entry.getValue());
                    healthVideo.setVideoId("PlayVideo/" + id);
                    HealthVideoPlayerActivity.gotoHealthVideoPlayerActivity(getActivity(), healthVideo);
                }
            });
        }

        @Override
        public int getItemCount() {
            return mMap.size();
        }
    }

    private class DataViewHolder extends RecyclerView.ViewHolder {

        TextView title;

        public DataViewHolder(@NonNull View itemView) {
            super(itemView);
            title = (TextView) itemView;
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mSearchTask != null) {
            mSearchTask.cancel(true);
        }
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
    }
}
